package com.liuchuanzheng.lcz_wanandroid

import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.ashokvarma.bottomnavigation.BottomNavigationBar
import com.ashokvarma.bottomnavigation.BottomNavigationItem
import com.liuchuanzheng.baselib.util.lcz.LCZUtil
import com.liuchuanzheng.lcz_wanandroid.base.BaseActivity
import com.liuchuanzheng.lcz_wanandroid.databinding.ActivityMainBinding
import com.liuchuanzheng.lcz_wanandroid.ui.fragment.HomeFragment
import com.liuchuanzheng.lcz_wanandroid.ui.fragment.QuestionFragment
import tech.linjiang.pandora.util.ViewKnife.dip2px

class MainActivity : BaseActivity() {
    lateinit var mViewBinding: ActivityMainBinding
    private var titleList: MutableList<String> = mutableListOf()
    private var fragments: MutableList<Fragment> = mutableListOf<Fragment>()
    override fun setContentView() {
        mViewBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mViewBinding.root)
    }

    override fun doYourself() {
        initViewPagerAndBottomBar()

    }

    private fun initViewPagerAndBottomBar() {
        titleList.run {
            add(resources.getString(R.string.home))
            add(resources.getString(R.string.system))
            add(resources.getString(R.string.weixin))
            add(resources.getString(R.string.question))
            add(resources.getString(R.string.my))
        }
        fragments.run {
            add(HomeFragment.newInstance())
            add(HomeFragment.newInstance())
            add(HomeFragment.newInstance())
            add(QuestionFragment.newInstance())
            add(HomeFragment.newInstance())
        }
        mViewBinding.viewPager.let { viewPager: ViewPager ->
            viewPager.adapter = MyMainPagerAdapter(supportFragmentManager, fragments)
            viewPager.offscreenPageLimit = fragments.size
            viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {

                }

                override fun onPageSelected(position: Int) {
                    mViewBinding.bottomBar.selectTab(position)
                }

                override fun onPageScrollStateChanged(state: Int) {

                }

            })
        }

        // 设置模式
        // MODE_FIXED 未选中item会显示文字 但不会有切换动画
        // MODE_SHIFTING 未选中的Item不会显示文字，选中的会显示文字 切换时会有动画
        mViewBinding.bottomBar.setMode(BottomNavigationBar.MODE_FIXED)
            // 设置导航栏背景风格
            //BACKGROUND_STYLE_STATIC 为点击无水波
            //BACKGROUND_STYLE_RIPPLE为点击有水波
            .setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC)
            .addItem(BottomNavigationItem(R.drawable.home, titleList[0]))
            .addItem(BottomNavigationItem(R.drawable.work, titleList[1]))
            .addItem(BottomNavigationItem(R.drawable.weixin, titleList[2]))
            .addItem(BottomNavigationItem(R.drawable.msg, titleList[3]))
            .addItem(BottomNavigationItem(R.drawable.my, titleList[4]))
            .setActiveColor(R.color.teal_200)//图标和文本未被激活或选中的颜色，默认颜色为Color.LTGRAY
            .setInActiveColor(R.color.black)//图标和文本激活或选中的颜色，默认颜色为Theme’s Primary Color
            .setBarBackgroundColor(R.color.white)//整个空控件的背景色，默认颜色为Color.WHITE
            .setTabSelectedListener(object : BottomNavigationBar.OnTabSelectedListener {
                override fun onTabSelected(position: Int) {
                    mViewBinding.viewPager.currentItem = position
                }

                override fun onTabUnselected(position: Int) {
                }

                override fun onTabReselected(position: Int) {
                }

            })
            .setFirstSelectedPosition(0)
            .initialise()
        setBottomNavigationItem(mViewBinding.bottomBar, 10, 22, 12)
        mViewBinding.viewPager.currentItem = 0
    }
    /**
     * @param bottomNavigationBar，需要修改的 BottomNavigationBar
     * @param space 图片与文字之间的间距
     * @param imgLen 单位：dp，图片大小，应 <= 36dp
     * @param textSize 单位：dp，文字大小，应 <= 20dp
     *
     * 使用方法：直接调用setBottomNavigationItem(bottomNavigationBar, 6, 26, 10);
     * 代表将bottomNavigationBar的文字大小设置为10dp，图片大小为26dp，二者间间距为6dp
     */
    private fun setBottomNavigationItem(
        bottomNavigationBar: BottomNavigationBar,
        space: Int,
        imgLen: Int,
        textSize: Int
    ) {
        val barClass: Class<*> = bottomNavigationBar.javaClass
        val fields = barClass.declaredFields
        for (i in fields.indices) {
            val field = fields[i]
            field.isAccessible = true
            if (field.name == "mTabContainer") {
                try {
                    //反射得到 mTabContainer
                    val mTabContainer = field[bottomNavigationBar] as LinearLayout
                    for (j in 0 until mTabContainer.childCount) {
                        //获取到容器内的各个Tab
                        val view = mTabContainer.getChildAt(j)
                        //获取到Tab内的各个显示控件
                        var params = FrameLayout.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            LCZUtil.dp2px( 56f)
                        )
                        val container =
                            view.findViewById<View>(R.id.fixed_bottom_navigation_container) as FrameLayout
                        container.layoutParams = params
                        container.setPadding(
                            LCZUtil.dp2px( 0F),
                            LCZUtil.dp2px(0f),
                            LCZUtil.dp2px( 0f),
                            LCZUtil.dp2px( 0f)
                        )
                        //获取到Tab内的文字控件
                        val labelView =
                            view.findViewById<View>(com.ashokvarma.bottomnavigation.R.id.fixed_bottom_navigation_title) as TextView
                        //计算文字的高度DP值并设置，setTextSize为设置文字正方形的对角线长度，所以：文字高度（总内容高度减去间距和图片高度）*根号2即为对角线长度，此处用DP值，设置该值即可。
                        labelView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, textSize.toFloat())
                        labelView.includeFontPadding = false
                        labelView.setPadding(0, 0, 0, LCZUtil.dp2px((25 - textSize - space / 2).toFloat()))
                        //获取到Tab内的图像控件
                        val iconView =
                            view.findViewById<View>(com.ashokvarma.bottomnavigation.R.id.fixed_bottom_navigation_icon) as ImageView
                        //设置图片参数，其中，MethodUtils.dip2px()：换算dp值
                        params =
                            FrameLayout.LayoutParams(LCZUtil.dp2px(imgLen.toFloat()), LCZUtil.dp2px(
                                imgLen.toFloat()
                            ))
                        params.setMargins(0, 0, 0, space / 2)
                        params.gravity = Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL
                        iconView.layoutParams = params
                    }
                } catch (e: IllegalAccessException) {
                    e.printStackTrace()
                }
            }
        }
    }

    class MyMainPagerAdapter : FragmentPagerAdapter {
        private var fragmentList: List<Fragment>? = null

        constructor(fm: FragmentManager?) : super(fm!!) {}
        constructor(fm: FragmentManager?, fragmentList: List<Fragment>?) : super(
            fm!!
        ) {
            this.fragmentList = fragmentList
        }

        override fun getItem(position: Int): Fragment {
            return fragmentList!![position]
        }

        override fun getCount(): Int {
            return if (fragmentList == null) 0 else fragmentList!!.size
        }
    }

}